package com.fl.ui;

import java.awt.EventQueue;
import java.awt.Font;
import java.awt.GraphicsEnvironment;
import java.awt.event.ActionEvent;

import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

import org.apache.log4j.Logger;
import org.jb2011.lnf.beautyeye.BeautyEyeLNFHelper;

import com.fl.serivce.FtpService;
import com.fl.serivce.LicenseService;
import com.fl.serivce.SysService;
import com.fl.sys.SysConfig;
import com.fl.util.ContentUtil;
import com.fl.util.StringUtil;

/**
 * @author liliang
 * 
 */
public class MainUI {

	private static final Logger log = Logger.getLogger(MainUI.class);

	private JFrame frame;
	private JTextField userTextField;
	private JPasswordField passwordField;
	private JTextField licenseTextField;
	private JLabel titleLabel;
	private JLabel userLabel;
	private JLabel passwordLabel;
	private JLabel licenseLabel;
	private JButton btnLicenseButton;
	private JButton btnLoginButton;
	private JButton btnLogoutButton;
	private final Action licenseAction = new LicenseAction();
	private final Action loginAction = new LoginAction();
	private final Action logoutAction = new LogoutAction();

	/**
	 * Create the application.
	 * 
	 * @throws UnsupportedLookAndFeelException
	 * @throws IllegalAccessException
	 * @throws InstantiationException
	 * @throws ClassNotFoundException
	 */
	public MainUI() throws ClassNotFoundException, InstantiationException,
			IllegalAccessException, UnsupportedLookAndFeelException {
		initialize();
	}

	/**
	 * Initialize the contents of the frame.
	 * 
	 * @throws UnsupportedLookAndFeelException
	 * @throws IllegalAccessException
	 * @throws InstantiationException
	 * @throws ClassNotFoundException
	 */
	private void initialize() throws ClassNotFoundException,
			InstantiationException, IllegalAccessException,
			UnsupportedLookAndFeelException {

		frame = new JFrame();
		frame.setTitle(ContentUtil.getString("MainTitle"));
		frame.setResizable(false);
		frame.setBounds(100, 100, 742, 433);
		frame.setLocationRelativeTo(null);
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		frame.getContentPane().setLayout(null);

		titleLabel = new JLabel(ContentUtil.getString("MainTitle"));
		titleLabel.setFont(new Font("宋体", Font.PLAIN, 38));
		titleLabel.setHorizontalAlignment(SwingConstants.CENTER);
		titleLabel.setBounds(191, 25, 312, 94);
		frame.getContentPane().add(titleLabel);

		userTextField = new JTextField();
		userTextField.setBounds(242, 150, 218, 27);
		frame.getContentPane().add(userTextField);
		userTextField.setColumns(10);

		passwordField = new JPasswordField();
		passwordField.setBounds(242, 180, 218, 27);
		frame.getContentPane().add(passwordField);

		licenseTextField = new JTextField();
		licenseTextField.setColumns(10);
		licenseTextField.setBounds(242, 210, 218, 27);
		frame.getContentPane().add(licenseTextField);

		userLabel = new JLabel(ContentUtil.getString("MainUser"));
		userLabel.setFont(new Font("宋体", Font.PLAIN, 20));
		userLabel.setHorizontalAlignment(SwingConstants.LEFT);
		userLabel.setBounds(132, 150, 100, 27);
		frame.getContentPane().add(userLabel);

		passwordLabel = new JLabel(ContentUtil.getString("MainPassword"));
		passwordLabel.setHorizontalAlignment(SwingConstants.LEFT);
		passwordLabel.setFont(new Font("宋体", Font.PLAIN, 20));
		passwordLabel.setBounds(132, 180, 100, 27);
		frame.getContentPane().add(passwordLabel);

		licenseLabel = new JLabel(ContentUtil.getString("MainLicense"));
		licenseLabel.setHorizontalAlignment(SwingConstants.LEFT);
		licenseLabel.setFont(new Font("宋体", Font.PLAIN, 20));
		licenseLabel.setBounds(132, 208, 100, 27);
		frame.getContentPane().add(licenseLabel);

		btnLicenseButton = new JButton();
		btnLicenseButton.setAction(licenseAction);
		btnLicenseButton.setBounds(470, 211, 95, 27);
		frame.getContentPane().add(btnLicenseButton);

		btnLoginButton = new JButton();
		btnLoginButton.setAction(loginAction);
		btnLoginButton.setBounds(365, 280, 95, 25);
		frame.getContentPane().add(btnLoginButton);

		btnLogoutButton = new JButton();
		btnLogoutButton.setAction(logoutAction);
		btnLogoutButton.setBounds(470, 280, 95, 25);
		frame.getContentPane().add(btnLogoutButton);

	}

	/**
	 * Launch the application.
	 */
	public static void main(String[] args) {

		try {
			// 初始化系统
			SysConfig.SysInit();

			// 设置改变窗口边框样式定义,修改成普通不透明边框
			BeautyEyeLNFHelper.frameBorderStyle = BeautyEyeLNFHelper.FrameBorderStyle.generalNoTranslucencyShadow;
			// 设置属性即可：true表示使用ToolBar.background颜色实现纯色填充背景，BeautyEye中此属性默认是false
			UIManager.put("ToolBar.isPaintPlainBackground", Boolean.TRUE);
			// 隐藏信息按钮
			UIManager.put("RootPane.setupButtonVisible", false);
			// 美化
			org.jb2011.lnf.beautyeye.BeautyEyeLNFHelper.launchBeautyEyeLNF();

			/**
			 * 此处开始判断是否允许进入工作界面，如果存在用户，密码，且能够登陆ftp，
			 * 同时存在注册码，且机器码正确，那么直接进入工作界面，否则展示登陆界面 要求验证相关信息
			 **/
			boolean canShowWorkUI = true;
			// 0 首次登陆，1用户名密码错误，2软件注册码错误
			int messageType = -1;
			String user = SysService.getUser();
			String passwd = SysService.getPassword();
			String license = SysService.getLicense();
			if (StringUtil.isBlank(user) || StringUtil.isBlank(passwd)
					|| StringUtil.isBlank(license)) {
				// 首次登陆
				canShowWorkUI = false;
				messageType = 0;
			}

			// 此处验证 是否ftp用户密码变更导致无法使用，通过登陆可以重置用户名、密码
			if (!StringUtil.isBlank(user) && !StringUtil.isBlank(passwd)
					&& !new FtpService().isValidUser(user, passwd)) {
				// 用户名、密码错误
				canShowWorkUI = false;
				messageType = 1;
			}

			// 此处验证 是否更换了机器导致无法使用，通过登陆可以重置软件注册码
			if (!StringUtil.isBlank(license) && !license.equals(LicenseService.makeLicense())) {
				// 软件注册码错误
				canShowWorkUI = false;
				messageType = 2;
			}

			if (canShowWorkUI) {

				// 直接运行工作界面
				EventQueue.invokeLater(new Runnable() {
					public void run() {
						try {
							// 验证成功，弹出工作界面
							new WorkUI(GraphicsEnvironment
									.getLocalGraphicsEnvironment()
									.getDefaultScreenDevice()
									.getDefaultConfiguration());
						} catch (Exception e) {
							log.error(e);
							// 错误打印出来
							JOptionPane.showMessageDialog(null, e.getMessage(),
									ContentUtil.getString("SystemErr"),
									JOptionPane.ERROR_MESSAGE);
						}
					}
				});
			} else {

				// 给予提示
				if (messageType == 0) {
					// 初次登陆
					JOptionPane.showMessageDialog(null,
							ContentUtil.getString("MainLoginFirst"),
							ContentUtil.getString("SystemInfo"),
							JOptionPane.INFORMATION_MESSAGE);
				} else if (messageType == 1) {
					// 用户名明码错误
					JOptionPane.showMessageDialog(null,
							ContentUtil.getString("MainValidUserErr"),
							ContentUtil.getString("SystemErr"),
							JOptionPane.ERROR_MESSAGE);
				} else if (messageType == 2) {
					// 软件注册码错误
					JOptionPane.showMessageDialog(null,
							ContentUtil.getString("MainValidLicenseErr"),
							ContentUtil.getString("SystemErr"),
							JOptionPane.ERROR_MESSAGE);
				}

				// 运行主界面
				EventQueue.invokeLater(new Runnable() {
					public void run() {
						try {
							MainUI window = new MainUI();
							window.frame.setVisible(true);
						} catch (Exception e) {
							log.error(e);
							// 错误打印出来
							JOptionPane.showMessageDialog(null, e.getMessage(),
									ContentUtil.getString("SystemErr"),
									JOptionPane.ERROR_MESSAGE);
						}
					}
				});
			}

		} catch (Exception e) {
			log.error(e);
			// 错误打印出来
			JOptionPane.showMessageDialog(null, e.getMessage(),
					ContentUtil.getString("SystemErr"),
					JOptionPane.ERROR_MESSAGE);
		}

	}

	private class LicenseAction extends AbstractAction {
		public LicenseAction() {
			putValue(NAME, ContentUtil.getString("MainMac"));
			putValue(SHORT_DESCRIPTION, ContentUtil.getString("MainMac"));
		}

		public void actionPerformed(ActionEvent e) {

			Object[] message = new Object[1];
			// 放一个不可编辑的text控件，方便用户copy机器码
			JTextField licenseTextField = new JTextField(
					LicenseService.getSerialNumber());
			licenseTextField.setEditable(false);
			message[0] = licenseTextField;
			String[] options = { ContentUtil.getString("MainMacComfirm") };
			JOptionPane.showOptionDialog(frame, message,
					ContentUtil.getString("MainGetMacTitle"),
					JOptionPane.DEFAULT_OPTION,
					JOptionPane.INFORMATION_MESSAGE, null, options, options[0]);

		}
	}

	private class LoginAction extends AbstractAction {
		public LoginAction() {
			putValue(NAME, ContentUtil.getString("MainLogin"));
			putValue(SHORT_DESCRIPTION, ContentUtil.getString("MainLogin"));
		}

		public void actionPerformed(ActionEvent e) {

			try {
				// // 校验用户是否为空
				// if (StringUtil.isBlank(userTextField.getText())) {
				// JOptionPane.showMessageDialog(frame,
				// ContentUtil.getString("MainUserNull"),
				// ContentUtil.getString("MainUserNull"),
				// JOptionPane.ERROR_MESSAGE);
				// return;
				// }
				//
				// // 校验密码是否为空
				// if (StringUtil.isBlank(passwordField.getText())) {
				// JOptionPane.showMessageDialog(frame,
				// ContentUtil.getString("MainPasswordNull"),
				// ContentUtil.getString("MainPasswordNull"),
				// JOptionPane.ERROR_MESSAGE);
				// return;
				// }
				//
				// // 校验用户名密码是否合理
				// if (!new FtpService().isValidUser(userTextField.getText()
				// .trim(), passwordField.getText().trim())) {
				// JOptionPane.showMessageDialog(frame,
				// ContentUtil.getString("MainUserOrPasswordErr"),
				// ContentUtil.getString("MainUserOrPasswordErr"),
				// JOptionPane.ERROR_MESSAGE);
				// return;
				// }
				//
				// // 校验注册码是否为空
				// if (StringUtil.isBlank(licenseTextField.getText())) {
				// JOptionPane.showMessageDialog(frame,
				// ContentUtil.getString("MainLicenseNull"),
				// ContentUtil.getString("MainLicenseNull"),
				// JOptionPane.ERROR_MESSAGE);
				// return;
				// }
				//
				// // 验证注册码是否合法
				// if (!licenseTextField.getText().trim()
				// .equals(LicenseService.makeLicense())) {
				// JOptionPane.showMessageDialog(frame,
				// ContentUtil.getString("MainLicenseErr"),
				// ContentUtil.getString("MainLicenseErr"),
				// JOptionPane.ERROR_MESSAGE);
				// return;
				// }
				//
				// // 校验成功，信息保存到数据库
				// SysService.saveUser(userTextField.getText().trim());
				// SysService.savePassword(passwordField.getText().trim());
				// SysService.saveLicense(licenseTextField.getText().trim());

				// 验证成功，弹出工作界面
				new WorkUI(GraphicsEnvironment.getLocalGraphicsEnvironment()
						.getDefaultScreenDevice().getDefaultConfiguration());
				// 关闭登陆界面
				frame.dispose();
			} catch (Exception e1) {
				log.error(e1);
				// 错误打印出来
				JOptionPane.showMessageDialog(frame, e1.getMessage(),
						ContentUtil.getString("SystemErr"),
						JOptionPane.ERROR_MESSAGE);
			}
		}
	}

	private class LogoutAction extends AbstractAction {
		public LogoutAction() {
			putValue(NAME, ContentUtil.getString("MainLogout"));
			putValue(SHORT_DESCRIPTION, ContentUtil.getString("MainLogout"));
		}

		public void actionPerformed(ActionEvent e) {
			// 退出所有线程
			System.exit(0);
		}
	}
}
